package com.liuyu.mall2.controller.admin;

import com.liuyu.mall2.entity.Category;
import com.liuyu.mall2.entity.Goods;
import com.liuyu.mall2.service.CategoryService;
import com.liuyu.mall2.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 刘宇
 * @classname GoodsController
 * @time 2025/4/22
 * @project mall2
 */
@Controller
@RequestMapping("/admin/goods")
public class GoodsController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GoodsService goodsService;
    @GetMapping("/add")
public String add(Model model){
      List<Category> categories = categoryService.list();
    model.addAttribute("categories",categories);
      return "goods_add";
}
@Value("${images.uploadPath}")
private String uploadPath;
@PostMapping("/add")
    public String add(Goods goods ,MultipartFile file){
    String fileName=file.getOriginalFilename();
    String suffix=fileName.substring(fileName.lastIndexOf("."));
    String newFileName= UUID.randomUUID().toString().replaceAll("-", "");
    File dest=new File(uploadPath+"\\"+newFileName+suffix);
    try {
        file.transferTo(dest);
    } catch (IOException e) {
        e.printStackTrace();
    }
    goods.setImage("http://localhost:8080/"+newFileName+suffix);
    //打印商品
    System.out.println("商品："+goods);
    goodsService.add(goods);
    return "success";
}
@GetMapping("/list")
    public String list(Model model){
    model.addAttribute("goodses",goodsService.findAll());
    return "goods_list";
}
    @GetMapping("listbypage")
    public String listByPage(@RequestParam(required = false, defaultValue = "1") Integer pageNo, Model model) {
        int page = 1;
        if (pageNo != null) {
            page = pageNo;
        }
        model.addAttribute("pageBean", goodsService.findByPage(page));
        return "goods_list";
    }
}


